import { NextRequest, NextResponse } from 'next/server';
import { verifyJwtToken } from './jwt';

export async function authMiddleware(request: NextRequest) {
  // 不需要验证的路径
  const publicPaths = ['/login', '/register', '/forgot-password', '/reset-password'];
  const isPublicPath = publicPaths.some(path => request.nextUrl.pathname.startsWith(path));
  
  // 静态资源和API路由不需要重定向
  if (
    request.nextUrl.pathname.startsWith('/_next') || 
    request.nextUrl.pathname.startsWith('/api') ||
    request.nextUrl.pathname.startsWith('/static') ||
    request.nextUrl.pathname === '/favicon.ico'
  ) {
    return NextResponse.next();
  }
  
  // 主页直接重定向到登录页或仪表板（避免额外重定向）
  if (request.nextUrl.pathname === '/') {
    const token = request.cookies.get('auth-token')?.value;
    const verifiedToken = token && (await verifyJwtToken(token));
    
    if (verifiedToken) {
      return NextResponse.redirect(new URL('/dashboard', request.url));
    } else {
      return NextResponse.redirect(new URL('/login', request.url));
    }
  }
  
  const token = request.cookies.get('auth-token')?.value;
  
  // 如果没有token但请求了受保护路径，直接检查
  if (!token && !isPublicPath) {
    // 添加一个标记以防止API循环重定向
    const url = new URL('/login', request.url);
    // 不再添加callbackUrl以减少URL复杂性
    return NextResponse.redirect(url);
  }
  
  // 如果有token尝试验证
  if (token) {
    try {
      // 验证Token
      const verifiedToken = await verifyJwtToken(token);
      
      // 用户已登录，但访问登录/注册页面，重定向到仪表板
      if (verifiedToken && isPublicPath) {
        return NextResponse.redirect(new URL('/dashboard', request.url));
      }
      
      // token无效但访问的是受保护页面，重定向到登录
      if (!verifiedToken && !isPublicPath) {
        // 删除可能失效的cookie
        const response = NextResponse.redirect(new URL('/login', request.url));
        response.cookies.delete('auth-token');
        return response;
      }
    } catch (error) {
      // Token验证出错，可能是无效token
      if (!isPublicPath) {
        const response = NextResponse.redirect(new URL('/login', request.url));
        response.cookies.delete('auth-token');
        return response;
      }
    }
  }
  
  return NextResponse.next();
} 